<?php

namespace app\admin\service\user_profile\repealArchive;

use app\admin\service\UserService;
use app\common\Message;
use app\model\archives_model\UserArchiveModel;
use app\model\ConsultOfflineModel;
use app\model\ConsultOnlineModel;
use app\model\DepartmentModel;
use app\model\InterfereUserModel;
use app\model\ProxyEvaluationResultModel;
use app\model\SelfEvaluationResultModel;
use app\model\TaskUserResultModel;
use app\model\UserModel;
use think\db\exception\DbException;
use think\Service;

class RepealArchiveService extends Service
{
    use Message;

    /**
     * 废除档案库列表
     * @param $data
     * @return true
     * @throws DbException
     */
    public function recordList($data): bool
    {
        $where = [
            ['unit_id','=',$data['unit_id']],
            ['role_mode','=',3],
        ];
        /*搜索条件-开始*/
        $searchKey = ['name','department_id','start_time'];
        foreach ($searchKey as $v) {
            if (check_array_key($v, $data)){
                switch ($v){
                    case 'name':
                        $where[] = ['name|username', 'like', '%' . $data[$v] . '%'];
                        break;
                    case 'department_id':
                        $where[] = ['department_id', '=', $data[$v]];
                        break;
                    case 'start_time':
                        $where[] = ['repeal_time', 'between', [$data['start_time'],$data['end_time']]];
                        break;
                }
            }
        }
        /*搜索条件-结束*/
        $where[] = ['is_repeal','=',1];
        $field = ['id,name,username,avatar,sex,province_name,age,phone,nation,city_name,area_name,department_id,unit_id,
        user_number,archive_update_time,time,student_status,id_card,status as acc_status,repeal_time'];
        $query = UserModel::query()->where($where);
        $list = $query->with(['departmentNameMode','unitName'])->field($field)->order('repeal_time','desc')->paginate($data['pageSize'])->toArray();
        if(count($list)>0){
            $UserService = new UserService($this->app);
            $DepartmentAffiliationAll = $UserService->getDepartmentAffiliationAll($data['unit_id']);
            $department_ids = array_column($list['data'], 'department_id');
            $DepartmentAdminAll = $UserService->getDepartmentAdminAll($department_ids);
            foreach ($list['data'] as &$item) {
                //部门归属
                $item['ascription_name'] = $DepartmentAffiliationAll[$item['department_id']]['ascription_name']??'';
                if($item['archive_update_time'] == null) $item['archive_update_time'] = $item['time'];
                //所在部门
                $item['department_name'] = $DepartmentAffiliationAll[$item['department_id']]['all_name']??'';
                //部门number（班级编号）
                $item['department_number'] = $DepartmentAffiliationAll[$item['department_id']]['number']??'';
                //部门管理员
                $item['department_admin'] = $DepartmentAdminAll[$item['department_id']]['user_name']??'';
            }
        }
        $list['ids'] = $query->column('id');
        $this->result = $list;
        $this->message = '操作成功！';
        return true;
    }

    /**
     * 废除档案库列表所有数据ID
     * @param $data
     * @return true
     * @throws DbException
     */
    public function recordListAll($data): bool
    {
        $where = [
            ['unit_id','=',$data['unit_id']],
            ['role_mode','=',3],
        ];
        /*搜索条件-开始*/
        $searchKey = ['name','department_id','start_time'];
        foreach ($searchKey as $v) {
            if (check_array_key($v, $data)){
                switch ($v){
                    case 'name':
                        $where[] = ['name|username', 'like', '%' . $data[$v] . '%'];
                        break;
                    case 'department_id':
                        $where[] = ['department_id', '=', $data[$v]];
                        break;
                    case 'start_time':
                        $where[] = ['repeal_time', 'between', [$data['start_time'],$data['end_time']]];
                        break;
                }
            }
        }
        /*搜索条件-结束*/
        $where[] = ['is_repeal','=',1];
        $field = ['id,name,username,avatar,sex,province_name,age,phone,nation,city_name,area_name,department_id,unit_id,
        user_number,archive_update_time,time,student_status,id_card,status as acc_status'];
        $list = UserModel::query()->where($where)->with(['departmentNameMode','unitName'])->field($field)->select();
        $list = $list ? $list->toArray() : ['data' => []];
        $this->result = $list;
        $this->message = '操作成功！';
        return true;
    }

    public function restoreRecord($data)
    {
        $user_ids = explode(',',$data['user_id']);
        $key = ['type'];
        foreach($key as $item){
            if(!check_array_key($item,$data)){
                $this->message = '缺少参数！';
                return false;
            }
        }
        if($data['role_mode']>2){
            $this->message = '暂无权限还原！';
            return false;
        }
        $is_repeal = 1;//显示
        switch ($data['type']) {
            case 0:
                //还原所有档案
                $models = [
                    'UserArchiveModel' => [['user_id', 'in', $user_ids], ['is_repeal', '=', 1]],
                    'SelfEvaluationResultModel' => [['uid', 'in', $user_ids], ['is_repeal', '=', 1]],
                    'TaskUserResultModel' => [['uid', 'in', $user_ids], ['is_repeal', '=', 1]],
                    'ProxyEvaluationResultModel' => [['uid', 'in', $user_ids], ['is_repeal', '=', 1]],
                    'InterfereUserModel' => [['uid', 'in', $user_ids], ['is_repeal', '=', 1], ['status', '=', 1]],
                    'ConsultOnlineModel' => [['uid', 'in', $user_ids], ['is_repeal', '=', 1]],
                    'ConsultOfflineModel' => [['uid', 'in', $user_ids], ['is_repeal', '=', 1]],
                ];
                $is_repeal = 0;//不显示
                break;
            case 1:
                // 还原基本信息
                $models = [
                    'UserArchiveModel' => [['user_id', '=', $data['user_id']], ['is_repeal', '=', 1]],
                ];
                break;
            case 2:
                // 还原个人自评档案
                $models = [
                    'UserArchiveModel' => [['user_id', '=', $data['user_id']], ['is_repeal', '=', 1], ['type_id', '=', 1]],
                ];
                break;
            case 3:
                // 还原测评档案
                $models = [
                    'SelfEvaluationResultModel' => [['uid', '=', $data['user_id']], ['is_repeal', '=', 1]],
                    'TaskUserResultModel' => [['uid', '=', $data['user_id']], ['is_repeal', '=', 1]],
                    'ProxyEvaluationResultModel' => [['uid', '=', $data['user_id']], ['is_repeal', '=', 1]],
                ];
                break;
            case 4:
                // 还原危机干预档案
                $models = [
                    'InterfereUserModel' => [['uid', '=', $data['user_id']], ['is_repeal', '=', 1], ['status', '=', 1]],
                ];
                break;
            case 5:
                // 还原咨询预约档案
                $models = [
                    'ConsultOnlineModel' => [['uid', '=', $data['user_id']], ['is_repeal', '=', 1]],
                    'ConsultOfflineModel' => [['uid', '=', $data['user_id']], ['is_repeal', '=', 1]],
                ];
                break;
        }
        foreach ($models as $modelName => $where) {
            switch ($modelName){
                case 'UserArchiveModel':
                    $model = new UserArchiveModel();
                    break;
                case 'SelfEvaluationResultModel':
                    $model = new SelfEvaluationResultModel();
                    break;
                case 'TaskUserResultModel':
                    $model = new TaskUserResultModel();
                    break;
                case 'ProxyEvaluationResultModel':
                    $model = new ProxyEvaluationResultModel();
                    break;
                case 'InterfereUserModel':
                    $model = new InterfereUserModel();
                    break;
                case 'ConsultOnlineModel':
                    $model = new ConsultOnlineModel();
                    break;
                case 'ConsultOfflineModel':
                    $model = new ConsultOfflineModel();
                    break;
            }
            $update = ['is_repeal' => 0];//改为正常报告
            $this->updateRepealStatus2($model, $where, $update);
        }
        //修改用户表is_repeal状态为：0【正常报告】(在废弃档案里隐藏对应的模块档案)。修改is_normal状态为：1【显示正常报告记录】
        UserModel::query()->where('id','in',$user_ids)->update(['is_repeal'=>$is_repeal,'repeal_time'=>time(),'is_normal'=>1]);
        $this->result = 1;
        $this->message = '操作成功！';
        return true;
    }
    //更新数据
    public function updateRepealStatus($model, $where, $update): void
    {
        //彻底删除废弃档案的数据
        $model->where($where)->update($update);
    }

    //更新数据
    function updateRepealStatus2($model, $where, $update): void
    {
        $tempWhere = $where;
        $tempWhere[1] = ['is_repeal','=',0];
        $temp = $model->where($tempWhere)->find();
        if(!empty($temp)){
            //先彻底删除正常档案的数据
            $model->where($tempWhere)->update(['is_del'=>1]);
        }
        //把废弃档案改为正常的档案
        $model->where($where)->update($update);
    }
    public function deleteRecord($data)
    {
        $user_ids = explode(',',$data['user_id']);
        $key = ['type'];
        foreach($key as $item){
            if(!check_array_key($item,$data)){
                $this->message = '缺少参数！';
                return false;
            }
        }
        if($data['role_mode']>2){
            $this->message = '暂无权限删除！';
            return false;
        }

        $is_repeal = 1;//显示
        switch ($data['type']) {
            case 0:
                // 删除所有
                $models = [
                    'UserArchiveModel' => [['user_id', 'in', $user_ids], ['is_repeal', '=', 1]],
                    'SelfEvaluationResultModel' => [['uid', 'in', $user_ids], ['is_repeal', '=', 1]],
                    'TaskUserResultModel' => [['uid', 'in', $user_ids], ['is_repeal', '=', 1]],
                    'ProxyEvaluationResultModel' => [['uid', 'in', $user_ids], ['is_repeal', '=', 1]],
                    'InterfereUserModel' => [['uid', 'in', $user_ids], ['is_repeal', '=', 1], ['status', '=', 1]],
                    'ConsultOnlineModel' => [['uid', 'in', $user_ids], ['is_repeal', '=', 1]],
                    'ConsultOfflineModel' => [['uid', 'in', $user_ids], ['is_repeal', '=', 1]],
                ];
                $is_repeal = 0; //不显示
                break;
            case 1:
                // 删除基本信息
                $models = [
                    'UserArchiveModel' => [['user_id', '=', $data['user_id']], ['is_repeal', '=', 1]],
                ];
                break;
            case 2:
                // 删除个人自评档案
                $models = [
                    'UserArchiveModel' => [['user_id', '=', $data['user_id']], ['is_repeal', '=', 1], ['type_id', '=', 1]],
                ];
                break;
            case 3:
                // 删除测评档案
                $models = [
                    'SelfEvaluationResultModel' => [['uid', '=', $data['user_id']], ['is_repeal', '=', 1]],
                    'TaskUserResultModel' => [['uid', '=', $data['user_id']], ['is_repeal', '=', 1]],
                    'ProxyEvaluationResultModel' => [['uid', '=', $data['user_id']], ['is_repeal', '=', 1]],
                ];
                break;
            case 4:
                // 删除危机干预档案
                $models = [
                    'InterfereUserModel' => [['uid', '=', $data['user_id']], ['is_repeal', '=', 1], ['status', '=', 1]],
                ];
                break;
            case 5:
                // 删除咨询预约档案
                $models = [
                    'ConsultOnlineModel' => [['uid', '=', $data['user_id']], ['is_repeal', '=', 1]],
                    'ConsultOfflineModel' => [['uid', '=', $data['user_id']], ['is_repeal', '=', 1]],
                ];
                break;
        }
        foreach ($models as $modelName => $where) {
            switch ($modelName){
                case 'UserArchiveModel':
                    $model = new UserArchiveModel();
                    break;
                case 'SelfEvaluationResultModel':
                    $model = new SelfEvaluationResultModel();
                    break;
                case 'TaskUserResultModel':
                    $model = new TaskUserResultModel();
                    break;
                case 'ProxyEvaluationResultModel':
                    $model = new ProxyEvaluationResultModel();
                    break;
                case 'InterfereUserModel':
                    $model = new InterfereUserModel();
                    break;
                case 'ConsultOnlineModel':
                    $model = new ConsultOnlineModel();
                    break;
                case 'ConsultOfflineModel':
                    $model = new ConsultOfflineModel();
                    break;
            }
            $update = ['is_del' => 1];
            $this->updateRepealStatus($model, $where, $update);
        }
        UserModel::query()->where('id','in',$user_ids)->update(['is_repeal'=>$is_repeal,'repeal_time'=>time()]);
        $this->result = 1;
        $this->message = '操作成功！';
        return true;
    }
}